package com.msh.automatic.android.api.controller.admin;

import com.alibaba.fastjson2.JSONObject;
import com.github.f4b6a3.uuid.UuidCreator;
import com.msh.automatic.android.api.entity.Task;
import com.msh.automatic.android.api.entity.TaskLog;
import com.msh.automatic.android.api.mapper.TaskLogMapper;
import com.msh.automatic.android.api.mapper.TaskMapper;
import com.msh.automatic.android.api.util.EmqxUtil;
import com.msh.automatic.android.api.util.RetUtil;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;

@Slf4j
@RestController("a_TaskController")
@RequestMapping("/a/task")
public class TaskController {

    @Resource
    TaskLogMapper taskLogMapper;
    @Resource
    TaskMapper taskMapper;

    @ApiOperation(value = "创建任务",notes = "")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Object log(@RequestBody TaskLog params) throws UnsupportedEncodingException {
        TaskLog taskLog = new TaskLog();
        taskLog.setId(UuidCreator.getTimeOrderedEpoch().toString());
        taskLog.setDeviceId(params.getDeviceId());
        taskLog.setTaskId(params.getTaskId());
        taskLog.setMessage("");
        taskLog.setStatus(TaskLog.TaskLogStatus.wait_push);
        taskLogMapper.insert(taskLog);
        return RetUtil.success(taskLog);
    }

    @ApiOperation(value = "推送任务",notes = "")
    @RequestMapping(value = "/push", method = RequestMethod.POST)
    public Object push(@RequestBody TaskLog params) throws UnsupportedEncodingException {
        TaskLog taskLog = taskLogMapper.selectById(params.getId());
        Task task = taskMapper.selectById(taskLog.getTaskId());
        JSONObject payload = new JSONObject();
        payload.put("task",task);
        payload.put("taskLog",taskLog);
        try{
            String messageid = EmqxUtil.publish("user/"+taskLog.getDeviceId(),payload.toJSONString());
            taskLog.setStatus(TaskLog.TaskLogStatus.push_success);
            taskLogMapper.updateById(taskLog);
        }catch (Exception e){
            taskLog.setMessage("推送任务到设备错误."+e.getMessage());
            taskLogMapper.updateById(taskLog);
            log.error("",e);
        }
        return RetUtil.success(taskLog);
    }

    @ApiOperation(value = "任务信息",notes = "")
    @RequestMapping(value = "/info", method = RequestMethod.POST)
    public Object info(@RequestBody TaskLog params) throws UnsupportedEncodingException {
        TaskLog taskLog = taskLogMapper.selectById(params.getId());
        return RetUtil.success(taskLog);
    }

}